//
//  MyOrderViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/28.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import Foundation
import HandyJSON

enum OrderStatus: Int, HandyJSONEnum {
    case all        = 0
    case waitPay    = 1
    case notStart   = 2
    case processing = 3
    case comment    = 4
    case cancel     = 5
    case finish     = 7
    case waitFinished = 8
    case refounding = 10
    
    case drug_not = -1
    case drug_waitPay = 401
    case drug_notShipped = 402
    case drug_shipped = 403
    case drug_receipted = 404
    case drug_waitReceive = 405
    case drug_received = 406
    
    func description(readyFlag: Int = 1) -> String {
        switch self {
        case .all, .drug_not: return ""
        case .notStart: return readyFlag == 1 ? "已报到" : "未开始"
        case .waitPay, .drug_waitPay: return "待支付"
        case .processing: return "进行中"
        case .comment: return "待评价"
        case .cancel: return "已取消"
        case .finish: return "已完成"
        case .waitFinished: return "已开方"
        case .refounding: return "退款中"
        case .drug_notShipped: return "未发货"
        case .drug_shipped: return "已发货"
        case .drug_receipted: return "已收货"
        case .drug_waitReceive: return "待领取"
        case .drug_received: return "已领取"
        }
    }
    
    func statusColor(readyFlag: Int = 1) -> UIColor {
        switch self {
        case .notStart: return readyFlag == 1 ? .main : .warning
        case .waitPay,
             .drug_waitPay,
             .refounding: return .warning
        case .processing,
             .waitFinished,
             .drug_shipped,
             .drug_received,
             .drug_receipted: return .main
        case .drug_waitReceive: return UIColor(hex: "#E99F0A")
        case .comment,
             .cancel,
             .all,
             .finish,
             .drug_not,
             .drug_notShipped: return .textGray
        }
    }
}

struct MyAdvisoryOrder: HandyJSON {
    var canDelete: Bool = false
    var canCancel: Bool = false
    var canSignIn: Bool = false
    var deptName: String?
    var doctorName: String?
    var hospitalName: String?
    var orderAmount: String?
    var orderNumber: String?
    var orderId: String?
    var orderStatus: Int = 0
    var patientId: String?
    var patientName: String?
    var remainPayTime: String?
    var remainTime: String?
    var scheduleStart: String?
    var queueNum: String?
    var diagnoseId: String?
    var diagnoseName: String?
    var endTime: String?
    var url: String?
    /// 0-不可以退款 1-可以退款
    var canRefund: Int = 0
    
    ///业务类型-1:咨询2:复诊
    var businessType : Int = 0
}

struct MyAdvisoryOrderViewModel {
    let models: [MyAdvisoryOrder]
    
    var showEmptyView: Bool { return models.count <= 0 }
    
    var numberOfRows: Int { return models.count }
    
    func viewModel(for indexPath: IndexPath) -> MyAdvisoryOrderRowViewModel {
        return MyAdvisoryOrderRowViewModel(model: models[indexPath.row])
    }
}

struct MyAdvisoryOrderRowViewModel {
    let model: MyAdvisoryOrder
    
    init(model: MyAdvisoryOrder) {
        self.model = model
        self.orderAmount = model.orderAmount ?? ""
    }
    
    var canDelete: Bool { return model.canDelete }
    var canCancel: Bool { return model.canCancel }
    var departmentName: String { return model.deptName ?? "" }
    var doctorName: String { return model.doctorName ?? "" }
    var hospitalName: String { return model.hospitalName ?? "" }
    var orderAmount: String
    var orderNumber: String { return model.orderNumber ?? "" }
    var orderId: String { return model.orderId ?? "" }
    var status: OrderStatus { return OrderStatus(rawValue: model.orderStatus) ?? .all }
    var patientId: String { return model.patientId ?? "" }
    var patientName: String { return model.patientName ?? "" }
    var remainPayTime: String { return model.remainPayTime ?? "" }
    var diagnoseId: String { return model.diagnoseId ?? "" }
    var diagnoseName: String { return model.diagnoseName ?? "" }
    var endTime: String { return model.endTime ?? "" }
    var url: String { return model.url ?? "" }
    /// 0-不可以退款 1-可以退款
    var canRefund: Int { return model.canRefund }
    
    var tipText: NSAttributedString {
        let attributes = [NSAttributedString.Key.foregroundColor: UIColor(hex: "#F54C4C")]
        let timeStr = Date.timeStampToString(timeStamp: remainPayTime.intValue)
        let text = "请在\(timeStr)内支付"
        let attrStr = NSMutableAttributedString(string: text)
        attrStr.setAttributes(attributes, range: NSRange(location: 2, length: timeStr.count))
        return attrStr
    }
    
    var cellHeight: CGFloat {
        switch status {
        case .waitPay: return 120
        case .processing: return canRefund == 0 ? 70 : 120
        case .comment: return 180
        default: return 70
        }
    }
}

struct MyAdvisoryOrderFinishModel: HandyJSON {
    ///诊断id
    var diagnoseId: String?
    /// 内容
    var comment: String?
    ///评分
    var score: Float?
    ///医生姓名
    var docName: String?
    ///医生id
    var docId: String?
    ///病情描述
    var descriptionInfo: String?
    ///医生职称
    var docJobTitle: String?
    ///主诊断
    var mainDiagnosis: String?
    ///医生建议
    var docProposal: String?
    ///结束时间
    var endTime: String?
    ///医院名
    var hosName: String?
    ///科室名
    var deptName: String?
    ///患者基本信息
    var patientInfo: String?
    ///医生处方权限 1：有  0：无
    var isPrescription: Int?
    ///订单ID
    var orderId: String?
    ///头像
    var avatar: String?
    /// 1-可以进入 0-不可以进入
    var canChat: Int = 0
    
    ///业务类型-1:咨询2:复诊
    var businessType: Int = 0
}

struct MyAdvisoryOrderFinishViewModel {
    init(model: MyAdvisoryOrderFinishModel) {
        self.model = model
        self.score = model.score ?? 0
    }   
    let model: MyAdvisoryOrderFinishModel
    ///诊断id
    var diagnoseId: String { return model.diagnoseId ?? "" }
    ///内容
    var comment: String {return model.comment ?? ""}
    
    ///评分
    var score: Float
    ///医生姓名
    var docName: String { return model.docName ?? "" }
    ///医生id
    var docId: String { return model.docId ?? "" }
    ///病情描述
    var descriptionInfo: String { return model.descriptionInfo ?? "" }
    ///医生职称
    var docJobTitle: String { return model.docJobTitle ?? "" }
    ///主诊断
    var mainDiagnosis: String { return model.mainDiagnosis ?? "" }
    ///医生建议
    var docProposal: String { return model.docProposal ?? "" }
    ///结束时间
    var endTime: String { return model.endTime ?? "" }
    ///医院名
    var hosName: String { return model.hosName ?? "" }
    ///科室名
    var deptName: String { return model.deptName ?? "" }
    ///患者基本信息
    var patientInfo: String { return model.patientInfo ?? "" }
    ///医生处方权限 1：有  0：无
    var isPrescription: Int { return model.isPrescription ?? 0 }
    ///订单ID
    var orderId: String { return model.orderId ?? "" }
    ///头像
    var avatar: String { return model.avatar ?? "" }
    var canChat: Bool { return model.canChat == 1 }
    var businessType: Int { return model.businessType  }
    var numberOfSection: Int { return 6 }
    var numberOfRows: Int { return 1 }
    func titleForEntrance(indexPath: IndexPath) -> String {
        switch indexPath.section {
        case 2: return "聊天记录"
        case 3: return "我的处方"
        case 4: return "我的病历"
        case 5: return "评价"
        default: return ""
        }
    }
    func starViewIsHidden(indexPath: IndexPath) -> Bool {
        switch indexPath.section {
        case 5: return false
        default: return true
        }
    }
    func arrowRightIsHidden(indexPath: IndexPath) -> Bool {
        if indexPath.section == 5, score > 0 {
            return true
        } else {
            return false
        }
        
    }
}

struct MyOrderViewModel {
    /// 获取云门诊订单列表
    static func getMyCloudOrder(userId: Int,
                                status: Int,
                                success: @escaping (_ models: [CloudOrderModel]) -> Void,
                                failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras: [String: Any] = [
            "userId": userId,
            "orderStatus": status
        ]
        YSGLog("云门诊订单列表 paras: \(paras)")
        HttpTool.shared.request(target: ApiManager.cloudOrderList(paras: paras), success: { (json, code) in
            YSGLog("云门诊订单列表 json: \(json)")
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<CloudOrderModel>.deserializeModelArrayFrom(json: json["data"].description) as? [CloudOrderModel] {
                    success(models)
                } else {
                    failure("请求数剧发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 获取图文咨询订单列表
    static func getMyAdvisoryOrder(userId: Int,
                                   status: Int,
                                   success: @escaping ( _ models: [MyAdvisoryOrder]) -> Void,
                                   failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras: [String: Any] = ["userId": userId, "orderStatus": status]
        HttpTool.shared.request(target: ApiManager.advisoryOrderList(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<MyAdvisoryOrder>.deserializeModelArrayFrom(json: json["data"].description) as? [MyAdvisoryOrder] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍候重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 删除订单
    static func cancelOrder(orderId: String, finished: @escaping (_ msg: String?, _ code: HttpCode) -> Void) {
        let paras = ["orderId": orderId]
        HttpTool.shared.request(target: ApiManager.cancelOrder(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
    
    /// 获取图文咨询未支付订单详情
    static func getAdvisoryOrderDetail(orderId: String, success: @escaping (_ model: MyAdvisoryOrder) -> Void, failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["orderId": orderId]
        HttpTool.shared.request(target: ApiManager.advisoryOrderDetail(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<MyAdvisoryOrder>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍候重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    ///获取图文咨询已完成订单详情
    static func getAdvisoryOrderDetailFinish(diagnoseId: String, success: @escaping (_ model: MyAdvisoryOrderFinishModel) -> Void, failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["diagnoseId": diagnoseId]
        HttpTool.shared.request(target: ApiManager.advisoryOrderDetailFinish(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<MyAdvisoryOrderFinishModel>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍候重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    ///评价图文咨询已完成订单
    static func getAdvisoryOrderEvaluate(orderId: String, score: String, comment:String ,success: @escaping (_ msg: String?) -> Void, failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["orderId": orderId, "score": score,"comment": comment]
        HttpTool.shared.request(target: ApiManager.advisoryOrderEvaluate(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                success(json["message"].description)
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 订单退款
    /// orderNumber: 订单编号
    /// isAdmin: 是否手动强制退款(1是 0否), app调用都传0
    static func orderRefound(orderNumber: String, isAdmin: Int = 0, finished: @escaping (Bool, String?) -> Void) {
        let paras: [String: Any] = [
            "orderNumber": orderNumber,
            "isAdmin": isAdmin
        ]
        HttpTool.shared.request(target: ApiManager.orderRefound(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                finished(false, json["message"].description)
            case .success:
                finished(true, nil)
            }
        }) { errorMsg in
            finished(false, errorMsg)
        }
    }
}
